package net.wisos.opn.search;

import java.util.Collection;
import java.util.List;

import org.apache.solr.client.solrj.SolrServer;
import org.apache.solr.common.SolrInputDocument;

import com.google.common.collect.Lists;

public abstract class Searcher<T> {
	public void add(T entity) {
		SolrServer server = getSolrServer();
		try {
			server.add(toDocument(entity));
			server.commit();
		} catch (Exception e) {
			throw new SearchException("添加文档至搜索服务器时发生异常.", e);
		}
	}

	public void add(Collection<T> entities) {
		if (entities != null && !entities.isEmpty()) {
			List<SolrInputDocument> docs = Lists
					.newArrayListWithCapacity(entities.size());
			for (T entity : entities) {
				docs.add(toDocument(entity));
			}
			SolrServer server = getSolrServer();
			try {
				server.add(docs);
				server.commit();
			} catch (Exception e) {
				throw new SearchException("添加文档至搜索服务器时发生异常.", e);
			}
		}
	}

	public void deleteById(String id) {
		SolrServer server = getSolrServer();
		try {
			server.deleteById(id);
		} catch (Exception e) {
			throw new SearchException("删除文档时发生异常.", e);
		}
	}

	public void deleteById(List<String> ids) {
		SolrServer server = getSolrServer();
		try {
			server.deleteById(ids);
		} catch (Exception e) {
			throw new SearchException("删除文档时发生异常.", e);
		}
	}

	public void deleteByQuery(String query) {
		SolrServer server = getSolrServer();
		try {
			server.deleteByQuery(query);
		} catch (Exception e) {
			throw new SearchException("删除文档时发生异常.", e);
		}
	}

	protected abstract SolrServer getSolrServer();

	protected abstract SolrInputDocument toDocument(T entity);

	protected abstract T toEntity(SolrInputDocument document);

}
